﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Da = VLUNewsData;
using DaMo = VLUNewsData.EntityDataModel;
using BuUt = VLUNewsBusiness.Utilities;
using BuRU = VLUNewsBusiness.VLURolesAndUsers;
using System.Collections;
using System.Data.Objects;

namespace VLUNewsBusiness.VLUNews
{
    public class HtmlContent
    {
        #region Base members
        private static HtmlContent _Instance = null;
        public static HtmlContent Instance()
        {
            if (_Instance == null) _Instance = new HtmlContent();
            return _Instance;
        }

        public static void Release()
        {
            if (_Instance != null)
                GC.SuppressFinalize(_Instance);
        }
        #endregion Base members

        #region Save
        public int Save(int pHtmlContentID, int pPortalID, int pSitemapID, string pTitle, string pDescription
            , string pContent, string pImage, int pOwnerID, int pSenderID, int pRecieverID, int pStatus, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                DaMo.VluNewsHtmlContent model = null;
                if (pHtmlContentID != -1)
                    ent.VluNewsHtmlContents.Where(p => p.HtmlContentID == pHtmlContentID).FirstOrDefault();
                if (model == null)
                {
                    model = new DaMo.VluNewsHtmlContent();
                    model.CreatedByUserID = pUserID;
                    model.CreatedOnDate = DateTime.Now;
                    ent.VluNewsHtmlContents.AddObject(model);
                }
                model.PortalID = pPortalID;
                model.SiteMapID = pSitemapID;
                model.Title = pTitle;
                model.Description = pDescription;
                model.Content = pContent;
                model.Image = pImage;
                model.SenderID = pSenderID;
                model.ReceiverID = pRecieverID;
                model.OwnerID = pOwnerID;
                model.Status = pStatus;

                model.LastModifiedByUserID = pUserID;
                model.LastModifiedOnDate = DateTime.Now;

                result = ent.SaveChanges();
            }// using.
            return result;
        }
        public int SaveNew(int pHtmlContentID, int pPortalID, int pSitemapID, string pTitle, string pDescription
            , string pContent, string pImage, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                DaMo.VluNewsHtmlContent model = null;
                if (pHtmlContentID != -1)
                    model = ent.VluNewsHtmlContents.Where(p => p.HtmlContentID == pHtmlContentID).FirstOrDefault();
                if (model == null)
                {
                    model = new DaMo.VluNewsHtmlContent();
                    ent.VluNewsHtmlContents.AddObject(model);
                    model.CreatedByUserID = pUserID;
                    model.CreatedOnDate = DateTime.Now;
                }
                else
                {
                    #region Copy News Version
                    //if (model.Status == (int)BuUt.StatusEnums.Sent)
                    //{
                    //    DaMo.VluNewsHtmlContentVersion version = new DaMo.VluNewsHtmlContentVersion();
                    //    ent.VluNewsHtmlContentVersions.AddObject(version);
                    //    version.Content = model.Content;
                    //    version.CreatedByUserID = model.CreatedByUserID;
                    //    version.CreatedOnDate = model.CreatedOnDate;
                    //    version.Description = model.Description;
                    //    version.HtmlContentID = model.HtmlContentID;
                    //    version.Image = model.Image;
                    //    version.IsPost = model.IsPost;
                    //    version.LastModifiedByUserID = model.LastModifiedByUserID;
                    //    version.LastModifiedOnDate = model.LastModifiedOnDate;
                    //    version.OwnerID = model.OwnerID;
                    //    version.PortalID = model.PortalID;
                    //    version.PostTime = model.PostTime;
                    //    version.ReceiverID = model.ReceiverID;
                    //    version.RolerID = model.RolerID;
                    //    version.SenderID = model.SenderID;
                    //    version.SiteMapID = model.SiteMapID;
                    //    version.Status = model.Status;
                    //    version.Title = model.Title;
                    //}
                    #endregion Copy News Version
                }
                model.PortalID = pPortalID;
                model.SiteMapID = pSitemapID;
                model.OwnerID = pUserID;
                model.SenderID = pUserID;
                model.RolerID = null;
                model.ReceiverID = null;
                model.Title = pTitle;
                model.Description = pDescription;
                model.Content = pContent;
                model.Image = pImage;
                model.Status = (int)BuUt.StatusEnums.Editing;

                model.LastModifiedByUserID = pUserID;
                model.LastModifiedOnDate = DateTime.Now;

                result = ent.SaveChanges();
                if (result == 1)
                    return model.HtmlContentID;
            }// using.
            return result;
        }
        public int SaveEditing(int pHtmlContentID, int pSitemapID, string pTitle, string pDescription
            , string pContent, string pImage, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                DaMo.VluNewsHtmlContent model = null;
                    model = ent.VluNewsHtmlContents.Where(p => p.HtmlContentID == pHtmlContentID).FirstOrDefault();
                model.SiteMapID = pSitemapID;
                model.Title = pTitle;
                model.Description = pDescription;
                model.Content = pContent;
                model.Image = pImage;

                model.LastModifiedByUserID = pUserID;
                model.LastModifiedOnDate = DateTime.Now;

                result = ent.SaveChanges();
                if (result == 1)
                    return model.HtmlContentID;
            }// using.
            return result;
        }
        public int SaveGet(int pHtmlContentID, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                DaMo.VluNewsHtmlContent model = ent.VluNewsHtmlContents.Where(p => p.HtmlContentID == pHtmlContentID).FirstOrDefault();
                #region Copy News Version
                if (model.Status == (int)BuUt.StatusEnums.Sent)
                {
                    DaMo.VluNewsHtmlContentVersion version = new DaMo.VluNewsHtmlContentVersion();
                    ent.VluNewsHtmlContentVersions.AddObject(version);
                    version.Content = model.Content;
                    version.CreatedByUserID = model.CreatedByUserID;
                    version.CreatedOnDate = model.CreatedOnDate;
                    version.Description = model.Description;
                    version.HtmlContentID = model.HtmlContentID;
                    version.Image = model.Image;
                    version.IsPost = model.IsPost;
                    version.LastModifiedByUserID = model.LastModifiedByUserID;
                    version.LastModifiedOnDate = model.LastModifiedOnDate;
                    version.OwnerID = model.OwnerID;
                    version.PortalID = model.PortalID;
                    version.PostTime = model.PostTime;
                    version.ReceiverID = model.ReceiverID;
                    version.RolerID = model.RolerID;
                    version.SenderID = model.SenderID;
                    version.SiteMapID = model.SiteMapID;
                    version.Status = model.Status;
                    version.Title = model.Title;
                }
                #endregion Copy News Version

                model.OwnerID = pUserID;
                model.SenderID = pUserID;
                model.RolerID = null;
                model.ReceiverID = null;
                model.Status = (int)BuUt.StatusEnums.Editing;

                model.LastModifiedByUserID = pUserID;
                model.LastModifiedOnDate = DateTime.Now;

                result = ent.SaveChanges();
                if (result == 2)
                    return model.HtmlContentID;
            }// using.
            return result;
        }
        public int SaveSentToRole2l(int pHtmlContentID, int pSenderID, int pRolerID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveSentToRole, pSenderID, DateTime.Now, (int)BuUt.StatusEnums.Sent, pSenderID, pRolerID, pHtmlContentID);
            }
            return result;
        }
        public int SaveSentToRole(int pHtmlContentID, int pSenderID, int pRolerID)
        {
            // Multi level.
            HtmlContentTracker.Instance().SaveSentToRole(pHtmlContentID, pSenderID, pRolerID);

            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveSentToRole, pSenderID, DateTime.Now, (int)BuUt.StatusEnums.Sent, pSenderID, pRolerID, pHtmlContentID);
            }
            return result;
        }

        public int SaveSentToUser2l(int pHtmlContentID, int pSenderID, int pRecieverID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveSentToUser, pSenderID, DateTime.Now, (int)BuUt.StatusEnums.Sent, pSenderID, pRecieverID, pHtmlContentID);
            }
            return result;
        }
        public int SaveSentToUser(int pHtmlContentID, int pSenderID, int pRecieverID)
        {
            // Multi level.
            HtmlContentTracker.Instance().SaveSentToUser(pHtmlContentID, pSenderID, pRecieverID);

            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveSentToUser, pSenderID, DateTime.Now, (int)BuUt.StatusEnums.Sent, pSenderID, pRecieverID, pHtmlContentID);
            }
            return result;
        }
        public int SaveReturned2l(int pHtmlContentID, int pSenderID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveReturned2l, pSenderID, DateTime.Now, (int)BuUt.StatusEnums.Returned, pSenderID, pHtmlContentID);
            }
            return result;
        }
        public int SaveReturned(int pHtmlContentID, int pSenderID)
        {
            // Multi level.
            int vRecieverID = HtmlContentTracker.Instance().GetRecieverID(pHtmlContentID, pSenderID);
            HtmlContentTracker.Instance().SaveReturned(pHtmlContentID, pSenderID, vRecieverID);
         
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveReturned, pSenderID, DateTime.Now, (int)BuUt.StatusEnums.Returned, pSenderID, vRecieverID, pHtmlContentID);
            }
            return result;
        }
        public int SaveApproved(int pHtmlContentID, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveApproved, pUserID, DateTime.Now, (int)BuUt.StatusEnums.Approved, pHtmlContentID);
            }
            return result;
        }
        public int SaveDowned(int pHtmlContentID, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveDowned, pUserID, DateTime.Now, (int)BuUt.StatusEnums.Downed, pHtmlContentID);
            }
            return result;
        }
        public int SaveDeleted(int pHtmlContentID, int pUserID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.ExecuteStoreCommand(BuUt.SqlString.SaveDeleted, pUserID, DateTime.Now, (int)BuUt.StatusEnums.Deleted, pHtmlContentID);
            }
            return result;
        }
        #endregion Save

        #region Get
        /// <summary>
        /// * Check sitemap is security. If true then the news not approve.
        /// </summary>
        /// <param name="pSitemapID"></param>
        /// <returns></returns>
        public bool CheckSitemap(int pSitemapID)
        {
            bool result = false;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.VluNewsSitemaps.Any(p => p.SiteMapID == pSitemapID && p.IsSecurity);
            }
            return result;
        }
        /// <summary>
        /// * Check ToRole = FromRole.
        /// </summary>
        /// <param name="pRoleID"></param>
        /// <returns></returns>
        public bool CheckTopRole(int pRoleID)
        {
            bool result = false;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                result = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
            }
            return result;
        }
        public bool CheckReceiver2l(int pHtmlContentID, int pUserID)
        {
            return false;
        }
        public bool CheckReceiver(int pHtmlContentID, int pUserID)
        {
            // Multi level.
            int vRecieverID = HtmlContentTracker.Instance().GetRecieverID(pHtmlContentID, pUserID);

            bool result = vRecieverID > 0;
            return result;
        }
        public bool CheckAllowToDown(int pHtmlContentID, int pUserID, int pRoleID)
        {
            bool result = false;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // If top Role.
                result = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
                // If Creater.
                if(!result)
                    result = ent.VluNewsHtmlContents.Any(p => p.HtmlContentID == pHtmlContentID && p.SenderID == pUserID && (!p.RolerID.HasValue && !p.ReceiverID.HasValue));
            }
            return result;
        }

        public bool CheckAllowToApprove(int pRoleID, int pSitemapID)
        {
            bool result = false;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // If top Role.
                result = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
                // If Creater.
                if (!result)
                    result = ent.VluNewsSitemaps.Any(p => p.SiteMapID == pSitemapID && !p.IsSecurity);
            }
            return result;
        }

        public IList<Array> GetsToRole(int pFromRoleID)
        {
            IList<Array> result = null;
            IQueryable<DaMo.VluNewsRoleToRole> query;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                query = ent.VluNewsRoleToRoles.Where(p => p.FromRoleID == pFromRoleID).OrderByDescending(p => p.ToRole.RoleName);
                if (query.Count() > 0)
                {
                    result = query.ToList().Select(p =>
                    new object[]
                    {
                        p.ToRoleID,
                        p.ToRole.RoleName,
                    }).ToList<Array>();
                }
            }
            return result;
        }
        public IList<Array> GetsRole(int pUserID)
        {
            IList<Array> result = null;
            IQueryable<DaMo.UserRole> query;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // Get NewsRoleGroupID.
                ObjectResult<string> oObjectResult = ent.ExecuteStoreQuery<string>(String.Format(BuUt.SqlString.getNewsRoleGroup, BuUt.BaseSettings.NewsRoleGroupName));
                int vRoleGroupID = int.Parse(oObjectResult.First());
                query = ent.UserRoles.Where(p => p.UserID == pUserID && p.Role.RoleGroupID == vRoleGroupID).OrderByDescending(p => p.Role.RoleName);
                if (query.Count() > 0)
                {
                    result = query.ToList().Select(p =>
                    new object[]
                    {
                        p.RoleID,
                        p.Role.RoleName,
                    }).ToList<Array>();
                }
            }
            return result;
        }

        public Array GetStatus(int pHtmlContentID, int pStatus)
        {
            Array result = null;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                var model = ent.VluNewsHtmlContents.Where(p => p.HtmlContentID == pHtmlContentID && p.Status == pStatus).FirstOrDefault();
                if (model != null)
                {
                    result = new object[] {
                        model.HtmlContentID, 
                        model.SiteMapID,
                        model.OwnerID,
                        model.Title, 
                        model.Description,
                        model.Content,
                        model.Image,
                        model.Owner.Username, 
                        model.LastModifiedOnDate 
                    };
                }
            }
            return result;
        }

        public int GetCountStatusAndSender2l(string pTitle, int pUserID, int pRoleID, int pStatus)
        {
            int result = 0;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                if (string.IsNullOrWhiteSpace(pTitle))
                    result = ent.VluNewsHtmlContents.Where(p => p.SenderID == pUserID && p.Status == (int)pStatus).Count();
                else
                    result = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID == pUserID && p.Status == (int)pStatus).Count();
            }
            return result;
        }
        public IList GetsStatusAndSender2l(string pTitle, int pUserID, int pRoleID, int pStatus, int pSkip, int pPageSize)
        {
            IList result = null;
            IQueryable<DaMo.VluNewsHtmlContent> query;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                if (string.IsNullOrWhiteSpace(pTitle))
                    query = ent.VluNewsHtmlContents.Where(p => p.SenderID == pUserID && p.Status == (int)pStatus)
                    .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                else
                    query = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID == pUserID && p.Status == (int)pStatus)
                    .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);

                if (query.Count() > 0)
                {
                    result = query.ToList().Select((p, index) =>
                    new
                    {
                        Order = index + 1,
                        p.HtmlContentID,
                        p.Title,
                        p.Description,
                        OwnerName = p.Sender.Username,
                        p.LastModifiedOnDate
                    }).ToList();
                }
            }
            return result;
        }

        public int GetCountStatusAndSender(string pTitle, int pUserID, int pRoleID, int pStatus)
        {
            // Multi level.
            List<int> htmlContentIDs = HtmlContentTracker.Instance().GetsHtmlContentIDBySender(pUserID, pRoleID);
            //List<int> lastHtmlContentIDs = HtmlContentTracker.Instance().GetsHtmlContentIDLastReceiver(pUserID, pRoleID);

            int result = 0;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                if (string.IsNullOrWhiteSpace(pTitle))
                    //result = ent.VluNewsHtmlContents.Where(p => p.SenderID == pUserID && p.Status == (int)pStatus).Count();
                    result = ent.VluNewsHtmlContents.Where(p => ((htmlContentIDs.Contains(p.HtmlContentID) && !((!p.RolerID.HasValue && p.ReceiverID == pUserID) || (!p.ReceiverID.HasValue && p.RolerID == pRoleID))) || p.SenderID == pUserID) && p.Status == (int)pStatus).Count();
                else
                    //result = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID == pUserID && p.Status == (int)pStatus).Count();
                    result = ent.VluNewsHtmlContents.Where(p => ((htmlContentIDs.Contains(p.HtmlContentID) && !((!p.RolerID.HasValue && p.ReceiverID == pUserID) || (!p.ReceiverID.HasValue && p.RolerID == pRoleID))) || p.SenderID == pUserID) && p.Status == (int)pStatus && p.Title.Contains(pTitle)).Count();
            }
            return result;
        }
        public IList GetsStatusAndSender(string pTitle, int pUserID, int pRoleID, int pStatus, int pSkip, int pPageSize)
        {
            // Multi level.
            List<int> htmlContentIDs = HtmlContentTracker.Instance().GetsHtmlContentIDBySender(pUserID, pRoleID);
            //List<int> lastHtmlContentIDs = HtmlContentTracker.Instance().GetsHtmlContentIDLastReceiver(pUserID, pRoleID);

            IList result = null;
            IQueryable<DaMo.VluNewsHtmlContent> query;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                if (string.IsNullOrWhiteSpace(pTitle))
                    query = ent.VluNewsHtmlContents.Where(p => ((htmlContentIDs.Contains(p.HtmlContentID) && !((!p.RolerID.HasValue && p.ReceiverID == pUserID) || (!p.ReceiverID.HasValue && p.RolerID == pRoleID))) || p.SenderID == pUserID) && p.Status == (int)pStatus)
                    .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                else
                    query = ent.VluNewsHtmlContents.Where(p => ((htmlContentIDs.Contains(p.HtmlContentID) && !((!p.RolerID.HasValue && p.ReceiverID == pUserID) || (!p.ReceiverID.HasValue && p.RolerID == pRoleID))) || p.SenderID == pUserID) && p.Status == (int)pStatus && p.Title.Contains(pTitle))
                    .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);

                if (query.Count() > 0)
                {
                    result = query.ToList().Select((p, index) =>
                    new
                    {
                        Order = index + 1,
                        p.HtmlContentID,
                        p.Title,
                        p.Description,
                        OwnerName = p.Sender.Username,
                        p.LastModifiedOnDate
                    }).ToList();
                }
            }
            return result;
        }

        public int GetCountStatusAndReceiver2l(string pTitle, int pUserID, int pRoleID, int pStatus)
        {
            int result = 0;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // If top Role.
                bool isTopRole = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
                if (isTopRole && (pStatus == (int)BuUt.StatusEnums.Approved || pStatus == (int)BuUt.StatusEnums.Downed || pStatus == (int)BuUt.StatusEnums.Deleted))
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        result = ent.VluNewsHtmlContents.Where(p => p.SenderID != pUserID && p.Status == (int)pStatus).Count();
                    else
                        result = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID != pUserID && p.Status == (int)pStatus).Count();
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        result = ent.VluNewsHtmlContents.Where(p => (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus).Count();
                    else
                        result = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus).Count();
                }
            }
            return result;
        }
        public IList GetsStatusAndReceiver2l(string pTitle, int pUserID, int pRoleID, int pStatus, int pSkip, int pPageSize)
        {
            IList result = null;
            IQueryable<DaMo.VluNewsHtmlContent> query;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // If top Role.
                bool isTopRole = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
                if (isTopRole && (pStatus == (int)BuUt.StatusEnums.Approved || pStatus == (int)BuUt.StatusEnums.Downed || pStatus == (int)BuUt.StatusEnums.Deleted))
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        query = ent.VluNewsHtmlContents.Where(p => p.SenderID != pUserID && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                    else
                        query = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID != pUserID && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        query = ent.VluNewsHtmlContents.Where(p => (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                    else
                        query = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                }
                if (query.Count() > 0)
                {
                    result = query.ToList().Select((p, index) =>
                    new
                    {
                        Order = index + 1,
                        p.HtmlContentID,
                        p.Title,
                        p.Description,
                        OwnerName = isTopRole ? p.Sender.Username : p.ReceiverID.HasValue ? p.Receiver.Username : "",
                        p.LastModifiedOnDate
                    }).ToList();
                }
            }
            return result;
        }

        public int GetCountStatusAndReceiver(string pTitle, int pUserID, int pRoleID, int pStatus)
        {
            int result = 0;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // If top Role.
                bool isTopRole = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
                if (isTopRole && (pStatus == (int)BuUt.StatusEnums.Approved || pStatus == (int)BuUt.StatusEnums.Downed || pStatus == (int)BuUt.StatusEnums.Deleted))
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        result = ent.VluNewsHtmlContents.Where(p => p.SenderID != pUserID && p.Status == (int)pStatus).Count();
                    else
                        result = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID != pUserID && p.Status == (int)pStatus).Count();
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        result = ent.VluNewsHtmlContents.Where(p => (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus).Count();
                    else
                        result = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus).Count();
                }
            }
            return result;
        }
        public IList GetsStatusAndReceiver(string pTitle, int pUserID, int pRoleID, int pStatus, int pSkip, int pPageSize)
        {
            IList result = null;
            IQueryable<DaMo.VluNewsHtmlContent> query;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                // If top Role.
                bool isTopRole = ent.VluNewsRoleToRoles.Any(p => p.FromRoleID == pRoleID && p.ToRoleID == pRoleID);
                if (isTopRole && (pStatus == (int)BuUt.StatusEnums.Approved || pStatus == (int)BuUt.StatusEnums.Downed || pStatus == (int)BuUt.StatusEnums.Deleted))
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        query = ent.VluNewsHtmlContents.Where(p => p.SenderID != pUserID && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                    else
                        query = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && p.SenderID != pUserID && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(pTitle))
                        query = ent.VluNewsHtmlContents.Where(p => (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                    else
                        query = ent.VluNewsHtmlContents.Where(p => p.Title.Contains(pTitle) && (p.ReceiverID == pUserID || p.RolerID == pRoleID) && p.Status == (int)pStatus)
                            .OrderByDescending(p => p.LastModifiedOnDate).Skip(pSkip).Take(pPageSize);
                }
                if (query.Count() > 0)
                {
                    result = query.ToList().Select((p, index) =>
                    new
                    {
                        Order = index + 1,
                        p.HtmlContentID,
                        p.Title,
                        p.Description,
                        //OwnerName = isTopRole? p.Sender.Username : p.ReceiverID.HasValue ? p.Receiver.Username : "",
                        OwnerName = p.ReceiverID.HasValue ? p.Receiver.DisplayName : p.RolerID.HasValue ? p.Role.RoleName : p.Sender.DisplayName,
                        p.LastModifiedOnDate
                    }).ToList();
                }
            }
            return result;
        }

        #region Remove
//        public IList GetsStatus(int pUserID, int pStatus)
//        {
//            IList result = null;
//            IQueryable<DaMo.VluNewsHtmlContent> query;
//            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
//            {
//                query = ent.VluNewsHtmlContents.Where(p => p.OwnerID == pUserID && p.Status == (int)pStatus).OrderByDescending(p => p.LastModifiedOnDate);
//                if (query.Count() > 0)
//                {
//                    result = query.ToList().Select((p, index) =>
//                    new
//                    {
//                        Order = index + 1,
//                        p.HtmlContentID,
//                        p.Title,
//                        p.Description,
//                        OwnerName = p.Owner.Username,
//                        p.LastModifiedOnDate
//                    }).ToList();
//                }
//#if (DEBUG)
//                System.Diagnostics.Debug.WriteLine(((System.Data.Objects.ObjectQuery)query).ToTraceString());
//#endif
//            }
//            return result;
//        }
//        /// <summary>
//        /// * Get with status = 1.
//        /// </summary>
//        /// <param name="pUserID"></param>
//        /// <returns></returns>
//        public IList GetsEditing(int pUserID)
//        {
//            return GetsStatus(pUserID, (int)BuUt.StatusEnums.Editing);
//        }
//        /// <summary>
//        /// * Get with status = 2.
//        /// </summary>
//        /// <param name="pUserID"></param>
//        /// <returns></returns>
//        public IList GetsSent(int pUserID)
//        {
//            return GetsStatus(pUserID, (int)BuUt.StatusEnums.Sent);
//        }
//        /// <summary>
//        /// * Get with status = 3.
//        /// </summary>
//        /// <param name="pUserID"></param>
//        /// <returns></returns>
//        public IList GetsApproved(int pUserID)
//        {
//            return GetsStatus(pUserID, (int)BuUt.StatusEnums.Approved);
//        }
//        /// <summary>
//        /// * Get with status = 4.
//        /// </summary>
//        /// <param name="pUserID"></param>
//        /// <returns></returns>
//        public IList GetsDowned(int pUserID)
//        {
//            return GetsStatus(pUserID, (int)BuUt.StatusEnums.Downed);
//        }
//        /// <summary>
//        /// * Get with status = 5.
//        /// </summary>
//        /// <param name="pUserID"></param>
//        /// <returns></returns>
//        public IList GetsDeleted(int pUserID)
//        {
//            return GetsStatus(pUserID, (int)BuUt.StatusEnums.Deleted);
//        }
        #endregion Remove
        #endregion Get

        #region Delete
        public int Delete(int pHtmlContentID)
        {
            int result = -1;
            using (DaMo.VLUNewsEntities ent = new DaMo.VLUNewsEntities())
            {
                DaMo.VluNewsHtmlContent model = ent.VluNewsHtmlContents.Where(p => p.HtmlContentID == pHtmlContentID).FirstOrDefault();
                #region Copy News Version
                DaMo.VluNewsHtmlContentVersion version = new DaMo.VluNewsHtmlContentVersion();
                ent.VluNewsHtmlContentVersions.AddObject(version);
                // Mark deleted in version.
                int status = (int)BuUt.StatusEnums.ForceDeleted;
                // Copy infor.
                version.Content = model.Content;
                version.CreatedByUserID = model.CreatedByUserID;
                version.CreatedOnDate = model.CreatedOnDate;
                version.Description = model.Description;
                version.HtmlContentID = model.HtmlContentID;
                version.Image = model.Image;
                version.IsPost = model.IsPost;
                version.LastModifiedByUserID = model.LastModifiedByUserID;
                version.LastModifiedOnDate = model.LastModifiedOnDate;
                version.OwnerID = model.OwnerID;
                version.PortalID = model.PortalID;
                version.PostTime = model.PostTime;
                version.ReceiverID = model.ReceiverID;
                version.RolerID = model.RolerID;
                version.SenderID = model.SenderID;
                version.SiteMapID = model.SiteMapID;
                version.Status = status;
                version.Title = model.Title;
                result = ent.SaveChanges();
                #endregion Copy News Version
                if (result == 1)
                {
                    result = ent.ExecuteStoreCommand(BuUt.SqlString.Delete, pHtmlContentID);
                    if (result > 0 && result < 4) //delete 3 table: VluNewsComment; VluNewsHtmlContentTracker; VluNewsHtmlContent.
                        return 1;// success.
                }
            }
            return result;
        }
        #endregion Delete
    }
}
